/**
 * 通用应用 Web 服务启动脚本
 */
const Vue = require('vue')
const express = require('express')
const fs = require('fs')
const {createBundleRenderer} = require('vue-server-renderer')
const setupDevServer = require('./build/setup-dev-server')

const server = express()

server.use('/dist', express.static('./dist'))

const isProd = process.env.NODE_ENV === 'production'

let renderer
let onReady
if (isProd) {
  // 生产模式
  const serverBundle = require('./dist/vue-ssr-server-bundle.json')
  const template = fs.readFileSync('./index.template.html', 'utf-8')
  const clientManifest = require('./dist/vue-ssr-client-manifest.json')

  renderer = createBundleRenderer(serverBundle, {
    template,
    clientManifest // （可选）客户端构建 manifest
  })
} else {
  // 开发模式 --> 监视源代码改动，重新打包构建  -->重新生成Renderer渲染器
  onReady = setupDevServer(server, (serverBundle, template, clientManifest) => {
    renderer = createBundleRenderer(serverBundle, {
      template,
      clientManifest // （可选）客户端构建 manifest
    })
  })
}

const render = async (req, res) => {
  try {
    const html = await renderer.renderToString({
      title: '拉勾教育',
      meta: `
        <meta name="description" content="拉勾教育">
      `,
    })
    res.setHeader('Content-Type', 'text/html; charset=utf8')
    res.end(html)
  } catch (err) {

    console.log(err)
    res.status(500).end('Internal Server Error.aaa')
  }
}

server.get('/', isProd
  ? render
  : async (req, res) => {
    // 等待renderer渲染器以后，去调用render去进行渲染
    await onReady
    render(req, res)
  }
)


server.listen(3000, () => {
  console.log('Server Running At Port 3000')
})